import os
import io
from pymongo import MongoClient
img_path = 'E:\\image_pi_new_p2\\'

client = MongoClient(port=27017)
db=client['tiktok_p2_2']
from google.oauth2 import service_account
from google.cloud import vision
credentials = service_account.Credentials.from_service_account_file('D:\\steel-cairn-344600-a9938c7de2a7.json')

client = vision.ImageAnnotatorClient(credentials=credentials )
collistt=['gaminglife', 'whatilearned', 'happyholi', 'stpatricksday', 'ontherunway', 'joblife', 'homecooked', 'tiktokcars', 'gettheretogether', 'zodiacsign', 'hellowinter', 'healthyheart', 'tiktokfood', 'petsontiktok', 'homecook', 'timewarpwaterfall', 'tiktokdiy', 'graphicdesign', 'holidaycrafts', 'foodtiktok', 'emophase', 'neontwin', 'tiktokwildlifeday', 'nflplayoffs', 'smallbusiness', 'needtoknow', 'superbowllv', 'mifamilia', 'nbaallstar', 'hyperfixated', 'couplethings', 'kissyourpet', 'greenscreenscan', 'tabletop', 'wildanimals', 'stemlife', 'easyrecipe', 'fallguysmoments', 'inkdrawing', 'gamenight', 'planttiktok', 'yellow', 'imaghost', 'mlkday', 'perfectmatch', 'homecafe', 'siblinggoals', 'whenwomenwin', 'promszn', 'halloweenlook', 'christmas2020', 'diyprojects', '2018vs2021', 'tiktokfashionmonth', 'theatrekids', 'mystyle', 'artmas', 'wrestlemania', 'cleaningtiktok', 'mypfp', 'holidaymusic', 'beautyhack', 'carsoftiktok', 'moneytok', 'homediy', 'holidaysourway', 'ratatouillemusical', 'happyhanukkah', 'colddays', 'thriftflip', 'carhacks', 'familyimpression', 'aprilfools', 'falldiy', 'recordsday', 'givingthanks', 'cartiktok', 'fallfashion', 'homeimprovement', 'crowdcheers', '2021affirmations', 'mobilegame', 'problemsolved', 'herstory', 'weirdpets', 'nbaisback', 'haventseen', 'baseballtiktok', 'ohno', 'clingypet', 'fantheory', 'coversforlovers', 'homemade', 'learnwithme', 'happyeaster', 'womeninstem', 'seashanty', 'somethingyoulearned', 'whenwewereyounger', 'vinylclub', 'productivity', 'animation', 'yearontiktok', 'coldweather', 'rareaesthetic', 'sidetable', 'onlinedating', 'puppybowl', 'perfectdrink', 'colorblast', 'sheesh', 'roomtour', 'thriftshop', 'sfxmakeup', 'housetour', 'perfectgifts', 'myrecommendation', 'nowruz', 'weekendvibes', 'givingszn', 'royalrumble', 'neonshadow', 'springvibes', 'learnontiktok', 'defrosting', 'doctorsoftiktok', 'healthycooking', 'dailyvlog', 'stylehacks', 'nhlfaceoff', 'ecohacks', 'catchphrases', 'wishlist', 'personalfinance', 'meditation101', 'diceroll', 'youwantmore', 'wordsofwisdom', 'upcycling', 'stepbystep', 'wip', 'baseballisback', 'welldone', 'onhold', 'unwrapthedeals', 'halloweenishere', 'notaperfectperson', 'typing', 'foodie', 'beautyhacks', 'inspirationalquotes', 'snowstorm', 'tipsandtricks', 'puppiesonly', 'fanedit', 'howbizarre', 'marchmadness', 'myhaul', 'meleaving', 'blackandproud', 'dayandnight', 'veteransday', 'fitnesslife', 'readysetshop', 'earthday', 'valentinesdiy', 'nonuancenovember', 'pleasedontgo', 'amongus', 'imbusyrightnow', 'naturescereal', 'holidaytiktok', 'itwasntaphase', 'winterfashion', 'melaninmagic', 'whereilive', 'laughingduet', 'winterfit', 'groupchat', 'myhobby', '90saesthetic', 'nowlookatthis', 'inlove', 'projectcar', 'relationshipstorytime', 'happyhalloween', 'yougotthis', 'galentinesday', 'welcome2021', 'motivationmonday', 'festivefashion', 'visionboard', 'comfortfood', 'givethanksnotpranks', 'fetapasta', 'horrortok', 'bekind', 'inverted', 'careeradvice', 'growupwithme', 'hellospring', 'feelinggood', 'sabiasque', 'isthisavailable', 'workingathome', 'goodmorning', 'bye2020', 'athletesoftiktok', 'takeabite', 'easydiy', 'watchmegrow', 'holidaydecor', 'seitan', 'myroutine', 'foodontiktok', 'holidaytreats', 'dinnerparty', 'gamergoals', 'tiktokfitness', 'vaccinatedfor', 'wintersports', 'sheearnedit', 'transvisibilityday', 'familyrecipe', 'cozyathome', 'gamingtiktok', 'raisedby', 'thankstoher', 'thinkingabout', 'healthyliving', 'plantparent', 'hereforrmhc', 'oscars', 'valentinesday', 'makeitvogue', 'lifestyle', 'happyholidays', 'lunarnewyear', 'olympicscountdown', 'bakingszn', 'competitivegaming', 'timewarpjump', 'homeproject', 'ourtype', 'cleantok', 'fitnessroutine', 'glasspainting', 'holidayvibes', 'blackcreatives', 'makeblackhistory', 'nativefamily', 'nbadraft', 'lovestory', 'dramaticmoments', 'tortillatrend', 'bakedoats', 'winterbeautytips', 'interiordesign', 'lookbook', 'holidaycountdown', 'ootd', 'selfimprovement', 'albumcover', 'passover', 'homebusiness', 'guitartok', 'tiktoktailgate', 'mycostume', 'science101', 'gamingsetup', 'homeoffice', 'springoutfit', 'rnbvibes', 'autismawareness', 'roundofapplause', 'passingthephone', 'tiktoktutorial', 'thrifting', 'songfacts', 'loveyourinsecurities', 'skincare101']
#for col in db.list_collection_names()[250:297]:
for col in collistt:
    for obj in db[col].find():
        for i in range(10):
            if len(obj['frame_level']['f'+str(i)]['img'])>0 and (type(obj['frame_level']['f'+str(i)]['text'])is dict):
                file_name = os.path.abspath('E:\\image_pi_new_p2\\'+obj['_id']+'_'+str(i)+'.jpg')
                with io.open(file_name, 'rb') as image_file:
                    content = image_file.read()
                image = vision.Image(content=content)
                response = client.text_detection(image=image)
                texts = response.text_annotations
                if response.error.message:
                    raise Exception(
                        '{}\nFor more info on error messages, check: '
                        'https://cloud.google.com/apis/design/errors'.format(
                            response.error.message))
                    exit
                if len(texts)==0:
                    db[col].update_one({'_id': obj['_id']},
                                       {'$set': {'frame_level.f' + str(i) + '.text': ''}})
                else:
                    db[col].update_one({'_id': obj['_id']},
                                       {'$set': {'frame_level.f' + str(i) + '.text': texts[0].description}})
                print('update success ',col,obj['_id'],i)

